package com.platform.common.web.domain;

import com.platform.common.web.utils.Pager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * json返回对象
 */
public class AjaxResult extends HashMap<String, Object> {

    /**
     * 成功
     */
    private static final Integer SUCCESS = 200;
    /**
     * 失败
     */
    private static final Integer FAIL = 201;
    /**
     * 登录错误
     */
    private static final Integer LOGIN_FAIL = 202;
    /**
     * 登录失效
     */
    private static final Integer LOGIN_DUE = 1001;

    /**
     * 状态码
     */
    public static final String CODE_TAG = "code";

    /**
     * 返回内容
     */
    public static final String MSG_TAG = "msg";

    /**
     * 数据对象
     */
    public static final String DATA_TAG = "data";

    /**
     * 数据列表
     */
    public static final String COUNT_TAG = "count";

    public AjaxResult(Integer code, String msg, Object data) {
        super();
        super.put(CODE_TAG, code);
        super.put(MSG_TAG, msg);
        if (data != null) {
            super.put(DATA_TAG, data);
        }
    }

    public static AjaxResult successMsg(String msg) {
        return new AjaxResult(SUCCESS, msg, null);
    }

    public static AjaxResult success() {
        return new AjaxResult(SUCCESS, "操作成功", null);
    }

    public static AjaxResult success(Object data) {
        AjaxResult r = new AjaxResult(SUCCESS, "操作成功", null);
        if (data instanceof List) {
            r.put(DATA_TAG, data);
            r.put(COUNT_TAG, Long.parseLong(String.valueOf(((List) data).size())));
        } else if (data instanceof Pager) {
            Pager pager = (Pager) data;
            r.put(DATA_TAG, pager.getDataList() == null ? new ArrayList<>() : pager.getDataList());
            r.put(COUNT_TAG, pager.getCount());
        } else {
            r.put(DATA_TAG, data);
        }
        return r;
    }

    public static AjaxResult fail(String msg) {
        return new AjaxResult(FAIL, msg, null);
    }

    public static AjaxResult loginFail(String msg) {
        return new AjaxResult(LOGIN_FAIL, msg, null);
    }

    public static AjaxResult loginDue(String msg) {
        return new AjaxResult(LOGIN_DUE, msg, null);
    }

    @Override
    public AjaxResult put(String key, Object value) {
        super.put(key, value);
        return this;
    }
}
